<template>
  <el-dialog
    :model-value="visible"
    title="添加审批人"
    width="50%"
    @close="handleClose"
  >
    <el-form :model="ruleForm" ref="ruleFormRef" label-width="100px" :rules="rules">
      <el-form-item label="成员" prop="userId">
        <el-select v-model="ruleForm.userId" style="width: 100%;" placeholder="请选择此审批节点成员" filterable multiple collapse-tags-tooltip>
          <el-option
            v-for="item in userList"
            :key="item.Id"
            :label="item.Name"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="addUser">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
export default { name: 'addUserDialog' }
</script>

<script setup>
import { ref, toRefs, reactive, onMounted, watch, defineProps, defineEmits, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { userHttp } from '@/utils/http/index';

const props = defineProps({
  dialogTitle: {
    type: String,
    default: "添加审批人"
  },
  visible: {
    type: Boolean,
    default: false
  },
})

const emits = defineEmits(['update:visible', 'addUserChange'])

let { visible } = toRefs(props)

const handleClose = () => {
  ruleFormRef.value.resetFields()
  userPageIndex.value = 1
  userList.value = []
  // 触发自定义事件来通知父组件关闭弹窗
  emits('update:visible', false)
}

/* 新增、编辑审批环节表单 */
const ruleFormRef = ref(null)
const ruleForm = ref({
  userId: "",
  userName: "",
})

/* 表单校验规则 */
const rules = reactive({
  userId: [
    { required: true, message: '请选择审批人', trigger: 'blur' }
  ],
})

const userList = ref([])
const userPageIndex = ref(1)
const userPageSize = ref(1000000)

/* 获取用户列表 */
const getPersonList = async () => {
  await userHttp.$GET(`/UserManager/GetUserList?pagenum=${userPageIndex.value}&pagesize=${userPageSize.value}`).then(res => {
    if(res.IsError) return ElMessage.warning("查询用户列表失败")
    userList.value = userList.value.concat(res.Result.content)
    if(userPageIndex.value < res.Result.total_num) {
      userPageIndex.value = userPageIndex.value + 1
      getPersonList()
    }
  })
}

defineExpose({
  getPersonList,
});

/* 提交审批 */
const addUser = () => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      let arr = getCommonObjects(ruleForm.value.userId, userList.value)

      let userIds = []
      let userNames = []

      arr.forEach((item) => {
        userIds.push(item.Id)
        userNames.push(item.Name)
      })

      /* let params = {
        userId: userIds.length ? userIds.join(",") : '',
        userName: userNames.length ? userNames.join(",") : ''
      } */

      emits('addUserChange', arr)
      emits('update:visible', false)
      setTimeout(() => {
        ruleFormRef.value.resetFields()
      }, 500)
    }else {
      ElMessage.warning("请先完成必填项")
    }
  })
}

const getCommonObjects = (arr1, arr2) => {
  let result = []
  for( let i = 0; i< arr2.length; i++ ){
    for( let j = 0; j < arr1.length; j++) {
      if(arr2[i].Id == arr1[j]) {
        result.push(arr2[i])
      }
    }
  }
  return result
}
</script>

<style lang='scss' scoped></style>